Modules


JavaScript modules allow you to break up your code into separate files, making it easier to maintain and organize. Modules are imported from external files with the import statement and exported using the export statement.

Exporting Modules

There are two types of exports: named exports and default exports.

Named Exports

Named exports allow you to export multiple values. You can create named exports in two ways:

// In-line individually
export const name = "John";
export const age = 30;

// All at once at the bottom
const name = "John";
const age = 30;
export { name, age };

Default Exports

Default exports allow you to export a single value or to have a fallback value for your module:

const message = () => {
    return "Hello, World!";
};
export default message;

Importing Modules

You can import modules into a file in two ways, based on whether they are named exports or default exports.

Importing Named Exports

import { name, age } from './person.js';

Importing Default Exports

import message from './message.js';

Example

Here is an example demonstrating how to use modules:

// person.js
export const name = "John";
export const age = 30;

// message.js
const message = () => {
    return `Hello, my name is ${name} and I am ${age} years old.`;
};
export default message;

// main.js
import { name, age } from './person.js';
import message from './message.js';

console.log(name); // John
console.log(age); // 30
console.log(message()); // Hello, my name is John and I am 30 years old.

For more detailed information, you can check out resources like W3Schools[^1^][1] and MDN Web Docs[^2^][2].